package com.ciwong.epaper.modules.epaper.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.ciwong.ciwongwrite.JournalActivity;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.dbbean.LswProgress;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.H5AnswersResponse;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.NewWorkScoreEvent;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.LswDao;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.epaper.util.RepeatKeyUtil;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.onlineanswer.OnlineAnswerPhotoBean;
import com.ciwong.epaper.modules.onlineanswer.OnlineAnswerSubMitResultBean;
import com.ciwong.epaper.modules.pigai.util.PigaiJumpManager;
import com.ciwong.epaper.ui.NewLoginActivity;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.utils.GsonUtil;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseRequestUtil;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.utils.fileprovider.FileProvider7;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.Gson;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.engine.SystemWebChromeClient;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 在线作答，作业
 * Created by yyf on 2017/6/7.
 */

public class NewWorkOnlineAnswerCordovaActivity extends BaseActivity implements SystemWebViewClient.LoadCallback, View.OnClickListener {
    /**
     * 唯一标识符
     */
//    private static final String TEMP_CAMERA_FILE = ESystem.getImagesPath(OnlineAnswerCordovaActivity.this) + File.separator + "temp.jpg";
    private static final int REQUEST_PERMISSION_CAMERA = 1;
    private String callbackId;
    private String answerJson;
    private int contentId;
    private long effectivDate;
    private String mJsonResPath;
    private ModuleContent moduleContent;
    /**
     * 1:作业进来，2：书桌进来
     */
    private int OnlineAnswerFrom = -1;
    public static final int FROM_HOME_WORK = 1;
    public static final int FROM_DESK = 2;
    /**
     * 网页展示内容
     */
    private String result;
    /**
     * 作业开始时间
     */
    private long startDate = System.currentTimeMillis();
    private DownLoadInfo mDownLoadInfo;
    private Module mModule;
    private long returnWorkLong;

    private int position;
    private String classId;
    private String workId = "0";
    protected int mServiceId;
    private UserInfoBase userInfo;
    private Answer tempAnswer;
    private Gson gson = new Gson();

    //做题记录
    protected String mUuid = UUID.randomUUID().toString();
    private H5AnswersResponse h5AnswersResponse;
    private String checkResource = "";
    private float mWorkSocre = 0;
    private int doWorkType = 0;
    private String errorResource = "";
    private String doWorkId = "";
    private int total;
    private WorkContents mWorkContent;
    private long startTime;

    private String mWorkCallbackId;

    @Override
    protected void onStart() {
        isjumpToResult = true;
        super.onStart();
    }

    @Override
    protected int setView() {
        return R.layout.activity_online_answer_cordova;
    }

    protected SystemWebView systemWebView;
    protected CordovaWebView cordovaWebView;
    /**
     * 提交中的界面
     */
    LinearLayout ll_submiting;
    RelativeLayout rel_submit_fail;
    Button btn_submit_again;

    @Override
    protected void findViews() {

        ll_submiting = (LinearLayout) findViewById(R.id.ll_submiting);
        systemWebView = (SystemWebView) findViewById(R.id.system_webview);
        systemWebView.getSettings().setBuiltInZoomControls(false);
        systemWebView.getSettings().setSavePassword(false);
        //android 11 上面google出于安全考虑，不推荐用webview直接访问文件，如果实际项目中有需要，就需要设置为true
        systemWebView.getSettings().setAllowFileAccess(true);
        //        systemWebView.setWebContentsDebuggingEnabled(true);
        btn_submit_again = (Button) findViewById(R.id.btn_submit_again);
        rel_submit_fail = (RelativeLayout) findViewById(R.id.rel_submit_fail);
    }

    @Override
    protected void init() {
        Intent intent = getIntent();

        //        TAG = "retryscore2";

        SystemWebViewEngine systemWebViewEngine = new SystemWebViewEngine(systemWebView);
        cordovaWebView = new CordovaWebViewImpl(systemWebViewEngine);
        ConfigXmlParser configXmlParser = new ConfigXmlParser();
        configXmlParser.parse(this);
        cordovaWebView.init(this, cordovaInterface, configXmlParser.getPluginEntries(), configXmlParser.getPreferences());
        SystemWebChromeClient systemWebChromeClient = new SystemWebChromeClient(systemWebViewEngine) {
            @Override
            public void onReceivedTitle(WebView view, String title) {//监听标题改变
                setTitleText(title);
                showBackBar();
            }
        };
        systemWebView.setWebChromeClient(systemWebChromeClient);
        systemWebView.getSettings().setDomStorageEnabled(true);//解决webview白板问题
        systemWebView.getSettings().setSavePassword(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            systemWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        handler.postDelayed(runnable, 1000);//每一秒执行一次runnable,作业耗时加一秒.

        mDownLoadInfo = (DownLoadInfo) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
        contentId = intent.getIntExtra(IntentFlag.INTENT_FLAG_ID, 0);
        OnlineAnswerFrom = intent.getIntExtra(IntentFlag.INTENT_FLAG_H5_PAGE_TYPE_SOURCE, -1);
        workId = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        effectivDate = intent.getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, 0);
        mModule = (Module) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_MODULE);
        position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
        moduleContent = (ModuleContent) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        checkResource = intent.getStringExtra(IntentFlag.INTENT_FLAG_CHECK_RESOURCE);
        mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
        mWorkSocre = getIntent().getFloatExtra(IntentFlag.INTENT_FLAG_WORK_SCORE, 0);
        errorResource = intent.getStringExtra(IntentFlag.INTENT_FLAG_ERROR_RESOURCE);
        doWorkId = intent.getStringExtra(IntentFlag.INTENT_FLAG_DO_WORK_ID);
        doWorkType = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_DO_WORK_TYPE, 0);
        mWorkContent = (WorkContents) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_WORK_CONTENTS);
        setValideSource(false);
        ALiYunManager.getInstance().registerListener(aLiYunListener);
        //获取保存本地的开始时间
        startTime = CWSys.getSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, workId), 0);
        //本地没有则使用传过来的时间 并保存本地
        if (startTime == 0) {
            if (null != mDownLoadInfo) {
                startTime = mDownLoadInfo.getStartTime();
                CWSys.setSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, workId), startTime);
            }
        }

        final String saveUUid = CWSys.getSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, 0), null);
        long strartTime = startDate;
        try {
            strartTime = CWSys.getSharedLong(RepeatKeyUtil.getStartDateSaveKey(mDownLoadInfo, mModule, position, workId, 0), startDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != saveUUid) {
            mUuid = saveUUid;
            startDate = strartTime;
            CWLog.e(TAG, "######null != saveUUid######" + saveUUid);
        } else {
            CWSys.setSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, 0), mUuid);
            CWSys.setSharedLong(RepeatKeyUtil.getStartDateSaveKey(mDownLoadInfo, mModule, position, workId, 0), startDate);
        }
        totalTime = (int) (System.currentTimeMillis() - startDate) / 1000;
        if (totalTime < 0) {
            int saveTotalTime = CWSys.getSharedInt(ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, workId, mUuid), -1);
            if (saveTotalTime != -1) {
                totalTime = saveTotalTime;
            }
        }
    }

    @Override
    protected void loadData() {
        showH5View();
        if (mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
            mJsonResPath = ESystem.getPackagesJsonPathNew(mDownLoadInfo.getBookId(), mDownLoadInfo.getChapterId(), mDownLoadInfo.getModuleId() + "", mDownLoadInfo.getVersionId());
        } else {
            mJsonResPath = mDownLoadInfo.mJsonResPath;
            //从扫一扫进来，moduleContent不为空
            if (moduleContent != null) {
                mJsonResPath = ESystem.getPackagesJsonPath(moduleContent.getResourceFile());

            }
        }

        if (TextUtils.isEmpty(mJsonResPath)) {
            ToastUtil.INSTANCE.toastCenterError("数据加载失败，请清除缓存后重试");
        }
        start_url = "file://" + ESystem.getOnlinePaperPath() + File.separator + "paper.html" + "?doWorkType=" + doWorkType;
        if (doWorkType == 1) {
            start_url = start_url + "&doWorkId=" + doWorkId;
        }
//        start_url = "https://m.teacher.jiaofuyun.com/modle_h5/onlinePaper/paper.html";//线上地址
//        start_url = "file:///storage/emulated/0/Android/data/com.ciwong.newspaper/cache/newspaper/onlinePaper2/onlinePaper/paper.html?doWorkType=0";
        CWLog.e("start_url:", start_url);
        cordovaWebView.loadUrl(start_url);
        showBackBar();
        checkSubmitFailAnswer();
        checkUnUpLoadPhotos();
    }

    /**
     * 检查未上传成功的图片
     */
    private void checkUnUpLoadPhotos() {
        String onLineAnswerPhotoKye = getOnLineAnswerPhotoKye();
        SerializableManager.getInstance().deSerialize(onLineAnswerPhotoKye, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                if (data != null) {
                    List<OnlineAnswerPhotoBean> unUpLoadPhotos = (List<OnlineAnswerPhotoBean>) data;
                    Iterator<OnlineAnswerPhotoBean> iterator = unUpLoadPhotos.iterator();
                    if (iterator.hasNext()) {
                        OnlineAnswerPhotoBean onlineAnswerPhotoBean = iterator.next();
                        if (new File(onlineAnswerPhotoBean.photoPath).exists()) {
                            ALiYunManager.getInstance().add(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
                        } else {
                            unUpLoadPhotos.remove(onlineAnswerPhotoBean);
                        }
                    }
                    onlineAnswerPhotoBeans.addAll(unUpLoadPhotos);
                    SerializableManager.getInstance().serialize(getOnLineAnswerPhotoKye(), null);
                }
                super.success(data);
            }
        });
    }


    @Override
    protected void initEvent() {
        EventBus.getDefault().register(this);
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                onBackPressed();
            }
        });
        btn_submit_again.setOnClickListener(this);

    }

    public void onEventMainThread(SubmitEvent submitEvent) {
        final String id = submitEvent.getId();
        final String callbackId = submitEvent.getCallbackId();
        Log.e(TAG, "onEventMainThread id: " + id);
        Log.e(TAG, "onEventMainThread callbackId: " + callbackId);
        if (id.equals("SetTitle")) {
            //            setTitle(submitEvent); //标题栏已经由H5提供，app端不用再显示标题
        } else if ("Submit".equals(id)) {
            //            提交作业(submitEvent);
        } else if (id.equals("GetOnlineExamination")) {//获取题目内容
            getOnlineExamination(callbackId);
        } else if (id.equals("GetOnlineAnswer")) {//获取用户答案
            getOnlineAnswer(callbackId);
        } else if (id.equals("SetOnlineAnswer")) {//保存答案到本地
            setOnlineAnswer(submitEvent.getJson());
        } else if (id.equals("SubmitOnlineAnswer")) {//提交答案到服务器
            String answerJson = submitEvent.getJson();
            submitOnlineAnswer(callbackId, answerJson);
        } else if (id.equals("ExitOnlineAnswer")) {//退出作答界面
            exitOnlineAnswer(submitEvent.getJson());
        } else if (id.equals("GetOnlineKey")) {//
            getOnlineKey(callbackId);
        } else if (id.equals("TakePhotoForText")) {
            mWorkCallbackId = callbackId;
            PigaiJumpManager.jumpToNewWorkPigaiStartActivity(NewWorkOnlineAnswerCordovaActivity.this, R.string.go_back);
        } else if (id.equals("TakePhotoForPad")) {
            TakePhotoForPad(submitEvent);
        } else if (id.equals("TakePhoto")) {
            TakePhoto(submitEvent);
        }
    }

    private static final int TAKE_PHOTOFORPAD = 4;

    public static final int PHOTO_REQUEST_CAMERA = 3;
    private String mCameraPath;

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_CAMERA:
                //                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                //
                //                }
                break;

            default:
                break;
        }
    }

    /**
     * 设置做作业进度
     */
    protected void setDoworkProgress(String answerJson) {
        if (effectivDate <= 0) {
            return;
        }
        if (OnlineAnswerFrom != 1 || doWorkType == 1) {//来自作业
            return;
        }
        int mQuesTotalIndex = 0;
        if (answerJson != null) {
            try {
                mQuesTotalIndex = 1;
                JSONObject jsonObject = new JSONObject(answerJson);
                String answerStr = jsonObject.getString("answers");
                JSONArray answerObject = new JSONArray(answerStr);
                mQuesTotalIndex = answerObject.length();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        LswProgress lswProgress = new LswProgress();
        lswProgress.setTotal(total);
        lswProgress.setWorkId(workId);
        lswProgress.setContentId(contentId);
        lswProgress.setEffectivDate(effectivDate);
        lswProgress.setProgress((mQuesTotalIndex));
        lswProgress.setWorkLong(totalTime);
        lswProgress.setUuid(mUuid);
        onUploadDoworkProgress(lswProgress);
    }

    private void onUploadDoworkProgress(final LswProgress lswProgress) {
        LswDao.getInstance().onUploadDoworkProgress(lswProgress, new BaseCallBack() {
            @Override
            public void success(Object data) {
                CWLog.d(TAG, "###########上传做作业进度成功############" + lswProgress.toString());
                CWSys.setSharedBoolean(RepeatKeyUtil.getStartDateIsUploadSaveKey(mDownLoadInfo, mModule, position, workId, 0), true);
            }

            @Override
            public void failed(int errorCode, Object data) {
                failed(data);
            }

            @Override
            public void failed(Object data) {

                CWLog.d(TAG, "###########上传做作业进度失败############" + lswProgress.toString());
                if (data != null) {
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, data.toString(), "听说模考上传语音评分失败：" + lswProgress.toString() + getUrl());
                }
            }
        });

    }

    private void TakePhotoForPad(SubmitEvent submitEvent) {
        try {
            String photoName = new JSONObject(submitEvent.getJson()).getString("fileName");
            mCameraPath = ESystem.getAnswersImagesPath("OnlineAnswerPic") + File.separator + photoName + ".png";
            callbackId = submitEvent.getCallbackId();
            Intent takePhotoForPadIntent = new Intent(this, JournalActivity.class);
            takePhotoForPadIntent.putExtra(JournalActivity.PHOTOPATH, mCameraPath);
            startActivityForResult(takePhotoForPadIntent, TAKE_PHOTOFORPAD);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void TakePhoto(SubmitEvent submitEvent) {
        try {
            String photoName = new JSONObject(submitEvent.getJson()).getString("fileName");
            mCameraPath = ESystem.getAnswersImagesPath("OnlineAnswerPic") + File.separator + photoName + EConstants.CAMERA_DEFAULT_SUFFIX;
            callbackId = submitEvent.getCallbackId();
            boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.CAMERA);
            //调用相机需要动态申请权限。
            if (isHavePermiss) {
                //有权限
                String tempCameraFile = ESystem.getImagesPath(NewWorkOnlineAnswerCordovaActivity.this) + File.separator + "temp.jpg";
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri fileUri = FileProvider7.getUriForFile(this, new File(tempCameraFile));
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                cameraIntent.putExtra("return-data", true);
                startActivityForResult(cameraIntent, PHOTO_REQUEST_CAMERA);
            } else {
                //无权限
                showgetCameraPermissDialog();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private CWDialog getCameraPermissDialog;

    /**
     * 获取Camera权限提示框
     */
    private boolean showgetCameraPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.CAMERA);
        if (isHavePermiss) {
            useCamera();
        } else {
            if (getCameraPermissDialog == null) {
                getCameraPermissDialog = new CWDialog(this);
                getCameraPermissDialog.setTitle(R.string.get_permiss_title);
                getCameraPermissDialog.setTitleTextColor(Color.BLACK);
                getCameraPermissDialog.setMessage(getString(R.string.get_camera_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getCameraPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                        useCamera();
                    }
                });
                getCameraPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                    }
                });
            }
            getCameraPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用照相机，判断权限
     */
    private void useCamera() {
        List<String> permissionList_camera = new ArrayList<String>();
        Map<String, String> noteMap_camera = new HashMap<>();
        noteMap_camera.put(Manifest.permission.CAMERA, "相机权限");
        permissionList_camera.add(Manifest.permission.CAMERA);
        if (Build.VERSION.SDK_INT >= 30) {
            permissionList_camera.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap_camera.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
        }
        XXPermissionTool.checkPermissions(this, //
                permissionList_camera, //
                noteMap_camera, //
                REQUEST_PERMISSION_CAMERA, //
                new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                    @Override
                    public void onCheckPermissionsFinished(int flag) {
                        if (0 == flag) {
                            String tempCameraFile = ESystem.getImagesPath(NewWorkOnlineAnswerCordovaActivity.this) + File.separator + "temp.jpg";
                            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri fileUri = FileProvider7.getUriForFile(NewWorkOnlineAnswerCordovaActivity.this, new File(tempCameraFile));
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            cameraIntent.putExtra("return-data", true);
                            startActivityForResult(cameraIntent, PHOTO_REQUEST_CAMERA);
                        }
                    }
                });
    }

    public void onEventMainThread(Answer answer) {
        CWLog.i("作业上传进度", answer.getProgress() + "提交状态" + answer.submitStatus);
    }


    public void onEventMainThread(NewWorkScoreEvent event) {
        CWLog.e("分数", GsonUtil.toJson(event));
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("doWorkId", event.doworkId);
            jsonObject.put("actualScore", event.actualScore);
            jsonObject.put("content", event.content);
            CWLog.d(TAG, "#######mWorkCallbackId ###########" + mWorkCallbackId + "发送数据" + jsonObject.toString());
            sendCallBackSuccess(mWorkCallbackId, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getOnLineAnswerKey() {

        String versionId = mDownLoadInfo.getVersionId();
        UserInfoBase userInfo = EApplication.getInstance().getUserInfoBase();
        String userId = "";
        if (null != userInfo) {
            userId = userInfo.getUserId() + "";
        }
        String key = versionId + mDownLoadInfo.getModuleId() + mDownLoadInfo.getChapterId() + workId + OnlineAnswerFrom + userId + EApplication.BRAND_ID + mUuid;
        if (mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
            return key;
        } else {
            if (moduleContent == null) {
                moduleContent = new ModuleContent();
                if (mModule != null && mModule.getResourceList() != null
                        && !mModule.getResourceList().isEmpty() && position < mModule.getResourceList().size() && position >= 0) {
                    moduleContent = mModule.getResourceList().get(position);
                }
            }
            String parentVersionId2 = ESystem.parse(moduleContent.getParentVersionId());
            String versionId2 = ESystem.parse(moduleContent.getVersionId());
            if (doWorkType == 1) {
                versionId2 = versionId2 + "_" + doWorkType;
            }
            return key + "_" + parentVersionId2 + "_" + versionId2;
        }
    }

    /**
     * 是否有主观题
     */
    private boolean isSubjective = false;

    /**
     * 提交作业
     *
     * @param callbackId
     * @param answerJson
     */
    private void submitOnlineAnswer(final String callbackId, String answerJson) {

        //        this.callbackId = callbackId;
        //        this.answerJson = answerJson;
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            return;
        }
        if (EConstants.IS_YOUKE) {

            NewLoginDialog newLoginDialog = new NewLoginDialog(NewWorkOnlineAnswerCordovaActivity.this);
            newLoginDialog.showLoginDialog();
            newLoginDialog.setNewLoginOnClickListener(new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == DialogInterface.BUTTON_POSITIVE) {
                        sendCallBackSuccess(callbackId, 1);
                    } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                        sendCallBackSuccess(callbackId, 1);
                    }

                }
            });
        } else {
            try {
                h5AnswersResponse = gson.fromJson(answerJson, H5AnswersResponse.class);

                int remainNum = Integer.parseInt(h5AnswersResponse.remainNum);
                if (remainNum > 0) {
                    String tips = "您还有" + remainNum + "道题目未完成，确定交卷吗？";
                    showConfirmCommitDialog(this, tips, callbackId, answerJson);
                } else {
                    submitAnswer(callbackId, answerJson);

                }
            } catch (Exception e) {
                submitAnswer(callbackId, answerJson);
            }
        }

    }

    private boolean isSubmiting = false;

    private void submitAnswer(final String callbackId, final String answerJson) {
        //先检查图片上传队列还有多少没上传完成。
        //        String answerAfter = "";
        //        //添加服务ID
        //        try {
        //            Answer orignalAnswer = gson.fromJson(answerJson, Answer.class);
        //            orignalAnswer.setWorkType(mServiceId);
        //            answerAfter = gson.toJson(orignalAnswer);
        //        }catch (Exception e){
        //            answerAfter = answerJson;
        //        }

        Log.d(TAG, "#######submitAnswer answerJson#########" + answerJson);
        this.answerJson = answerJson;
        String onLineAnswerKey = RepeatKeyUtil.getOnlineCommitAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);
        Log.d(TAG, "###########onLineAnswerKey#########" + onLineAnswerKey);
        SerializableManager.getInstance().serialize(onLineAnswerKey, answerJson);

        ESystem.setSharedString(getOnLineAnswerKey(), callbackId);
        sendCallBackSuccess(callbackId, 1);

        showSubmitView();
        for (OnlineAnswerPhotoBean onlineAnswerPhotoBean : onlineAnswerPhotoBeans) {
            if (TextUtils.isEmpty(onlineAnswerPhotoBean.photoUrl)) {//没有url说明上传还未完成
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("callbackId", callbackId);
                bundle.putString("answerJson", answerJson);
                message.setData(bundle);
                ALiYunManager.getInstance().addPic(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
                upLoadPicHandler.sendMessageDelayed(message, 2000);
                return;
            }
        }
        final Answer answer = getAnswer(answerJson);
        answer.setWorkType(mServiceId);
        if (doWorkType == 1) {
            answer.setErrorWorkId(doWorkId);
        }
        final String saveUUid = CWSys.getSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, 0), null);
        if (saveUUid != null) {
            Log.d(TAG, "#######saveUUid != null##########");

            answer.setSessionId(saveUUid);
        } else {
            Log.d(TAG, "#######saveUUid == null clearRecord() ##########");

            clearRecord();
            finish();
            return;
        }

        final String 最终提交的答案Json = gson.toJson(answer);

        Log.d(TAG, "#######最终提交的答案Json#########" + 最终提交的答案Json);
        showSubmitView();
        EpaperDao.getInstance().submitWork(最终提交的答案Json, doWorkType, answer, new BaseExtCallBack(this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                //                showToastError("答案提交失败，请重试");
                if (errorCode == 105) {
                    clearRecord();
                    finish();
                } else {
                    CWLog.i("答案提交失败errorCode:" + errorCode, data.toString());

                    Log.d(TAG, "#######failed errorCode#########" + errorCode);

                    if (null != data) {
                        FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_ONLINE_ANSWER, data.toString(), 最终提交的答案Json, "线上作答提交作业失败" + getUrl());
                        CWLog.d(TAG, "#######failed errorCode#########" + data.toString());
                    }

                    if (errorCode != EConstants.ERROR_CODE_REPEAT_COMMIT) {
                        showSubmitFailView();
                        //                    SerializableManager.getInstance().serialize(getOnLineAnswerKey(), answerJson);
                        //                    ESystem.setSharedString(getOnLineAnswerKey(), callbackId);
                        //                    sendCallBackSuccess(callbackId, 0);
                    } else {
                        //                    MeJumpManager.jumpToOnlineAnswerResultActivity(OnlineAnswerCordovaActivity.this, OnlineAnswerFrom, totalTime, onlineAnswerSubMitResultBean.doWorkId, answer.workScore, onlineAnswerSubMitResultBean.score, isSubjective, contentId + "");
                        ToastUtil.INSTANCE.toastCenterSuccess("提交成功！");
                        //通知刷新作业列表
                        sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
                        sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
                        clearRecord();
                        finish();

                    }
                }


            }

            @Override
            public void failed(Object data) {
                Log.d(TAG, "#######failed #########" + answerJson);
                FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_ONLINE_ANSWER, data.toString(), 最终提交的答案Json, "线上作答提交作业失败" + getUrl());
                //                SerializableManager.getInstance().serialize(getOnLineAnswerKey(), answerJson);
                //                ESystem.setSharedString(getOnLineAnswerKey(), callbackId);
                CWLog.i("答案提交失败", data.toString());
                showSubmitFailView();
                //                sendCallBackSuccess(callbackId, 0);
            }

            @Override
            public void success(Object data) {
                OnlineAnswerSubMitResultBean onlineAnswerSubMitResultBean = (OnlineAnswerSubMitResultBean) data;
                isSubjective = onlineAnswerSubMitResultBean.isHasNoCorrect();
                returnWorkLong = onlineAnswerSubMitResultBean.getWorkLong();
                answer.actualScore = onlineAnswerSubMitResultBean.getScore();
                //                sendCallBackSuccess(callbackId, 1);

                Log.d(TAG, "#######success #########");
                //                SerializableManager.getInstance().serialize(getOnLineAnswerKey(), "");
                //                ESystem.setSharedString(getOnLineAnswerKey(), "");
                clearRecord();
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
                if (isjumpToResult) { //如果当前activity还在前台就跳转。
                    MeJumpManager.jumpToOnlineAnswerResultActivity(NewWorkOnlineAnswerCordovaActivity.this, OnlineAnswerFrom, totalTime, onlineAnswerSubMitResultBean.getDoWorkId(), answer.workScore, onlineAnswerSubMitResultBean.getScore(), isSubjective, contentId + "", mDownLoadInfo, doWorkType, effectivDate, mWorkContent, returnWorkLong);
                    finish();
                }
                isSubmiting = false;
            }
        });
    }

    private boolean isjumpToResult = true;

    private void checkSubmitFailAnswer() {
        //        String readKey=getOnLineAnswerKey();

        String onLineAnswerKey = RepeatKeyUtil.getOnlineCommitAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);
        CWLog.e(TAG, "###########onLineAnswerKey#########" + onLineAnswerKey);

        SerializableManager.getInstance().deSerialize(onLineAnswerKey, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                if (data != null) {
                    NewWorkOnlineAnswerCordovaActivity.this.answerJson = String.valueOf(data);

                    Log.d(TAG, "#######this.answerJson answer###########" + answerJson);
                    callbackId = ESystem.getSharedString(getOnLineAnswerKey());
                    if (!TextUtils.isEmpty(answerJson) && !TextUtils.isEmpty(callbackId)) {
                        showSubmitFailView();
                    }
                }
            }
        });
    }

    private void exitOnlineAnswer(String answerJson) {
        String onLineAnswerKey = RepeatKeyUtil.getOnlineAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);
        String onLineAnswerPhotoKye = getOnLineAnswerPhotoKye();
        Log.d(TAG, "#####BaseRequestUtil.getInstance().cancelAll#####" + workId);
        BaseRequestUtil.getInstance().cancelAll(workId);
        String saveTimeKey = ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, workId, mUuid);
        DialogUtil.showConfirmEndOnlineAnswerDialog(NewWorkOnlineAnswerCordovaActivity.this, answerJson, onLineAnswerKey, isSubmiting, onLineAnswerPhotoKye, onlineAnswerPhotoBeans, saveTimeKey, totalTime);

    }

    private String getOnLineAnswerPhotoKye() {
        return getOnLineAnswerKey() + "photo";

    }

    private Answer getAnswer(String H5传来的answerJson) {

        tempAnswer = new Answer();
        tempAnswer.setContentId(contentId);
        tempAnswer.setDoWorkPackageUrl("");
        EApplication application = (EApplication) getBaseApplication();
        Clazz clazz = application.getClazz();
        userInfo = application.getUserInfoBase();
        if (null != userInfo && null != H5传来的answerJson) {
            if (TextUtils.isEmpty(workId)) {
                workId = "0";
            }
            tempAnswer.setWorkId(workId);
            tempAnswer.setWorkLong(totalTime);
            tempAnswer.setStartTime(startTime);
            if (clazz == null) {
                classId = "0";
            } else {
                classId = clazz.getClassId() + "";
            }
            tempAnswer.setClassId(classId);
            tempAnswer.setUserName(userInfo.getRealName());

            if (null != h5AnswersResponse) {
                tempAnswer.remainNum = h5AnswersResponse.remainNum;
            }

            try {
                JSONObject jsonObject = new JSONObject(H5传来的answerJson);

                tempAnswer.setWorkAnswers(jsonObject.getString("answers"));
                JSONObject resultJsonObject = new JSONObject(result);
                String ref_score = "";
                if (mWorkSocre != 0) {
                    ref_score = mWorkSocre + "";
                } else {
                    ref_score = resultJsonObject.getString("ref_score");
                }
                tempAnswer.setWorkScore(Float.parseFloat(ref_score));
            } catch (Exception e) {
                tempAnswer.setWorkAnswers("[]");
            }
            tempAnswer.setJsonVersion(EConstants.JSON_VERSION);
            tempAnswer.setUserAnswer(ESystem.USER_ANSWER);
            tempAnswer.setCreateTime(System.currentTimeMillis());
            tempAnswer.setBrandId(EApplication.BRAND_ID);
            int moduleId;

            if (moduleContent != null) {
                moduleId = mModule.getModuleInfo().getModuleId();
                tempAnswer.setResourceName(moduleContent.getResourceName());
                tempAnswer.setVersionId(moduleContent.getVersionId());
                tempAnswer.setParentVersionId(moduleContent.getParentVersionId());
                tempAnswer.setModuleId(moduleId);
                tempAnswer.setResourceType(moduleContent.getResourceType());
                //
                mDownLoadInfo.setVersionId(moduleContent.getVersionId());
                mDownLoadInfo.setResourceType(moduleContent.getResourceType());
                mDownLoadInfo.setModuleId(moduleId + "");
                mDownLoadInfo.setResourceName(moduleContent.getResourceName());


            } else {
                if (mDownLoadInfo != null) {
                    moduleId = Integer.parseInt(mDownLoadInfo.getModuleId());
                    tempAnswer.setResourceName(mDownLoadInfo.getResourceName());
                    tempAnswer.setResourceType(mDownLoadInfo.getResourceType());
                    tempAnswer.setVersionId(mDownLoadInfo.getVersionId());
                    tempAnswer.setModuleId(moduleId);
                }
            }
            if (mDownLoadInfo != null) {
                tempAnswer.setPackageId(mDownLoadInfo.getBookId());
                tempAnswer.setcId(mDownLoadInfo.getChapterId());
            }


        }
        return tempAnswer;
    }

    /**
     * 设置用户已经作答的答案
     */
    private void setOnlineAnswer(String answer) {
        String onLineAnswerKey = RepeatKeyUtil.getOnlineAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);
        CWLog.d(TAG, "#######setOnlineAnswer answer###########" + answer);
        SerializableManager.getInstance().serialize(onLineAnswerKey, answer);
        String saveTimeKey = ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, workId, mUuid);
        CWSys.setSharedInt(saveTimeKey, totalTime);
        //上报做题进度
        setDoworkProgress(answer);
    }

    private void getOnlineAnswer(final String callbackId) {
        SerializableManager.getInstance().deSerialize(RepeatKeyUtil.getOnlineAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid), new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                sendCallBackSuccess(callbackId, "");
            }

            @Override
            public void failed(Object data) {
                sendCallBackSuccess(callbackId, "");
            }

            @Override
            public void success(Object data) {
                String onlineAnswer = data.toString();
                Log.d(TAG, "#######getOnlineAnswer onlineAnswer#########" + onlineAnswer);
                if (EConstants.IS_YOUKE) {
                    sendCallBackSuccess(callbackId, "");
                } else {
                    sendCallBackSuccess(callbackId, onlineAnswer);
                }


            }
        });
    }

    private void getOnlineKey(String callbackId) {
        String onLineAnswerKey = getOnLineAnswerKey();
        sendCallBackSuccess(callbackId, onLineAnswerKey);
    }

    public String start_url = "";
    //    private String mDoWorkId;


    /**
     * 做作业耗时
     */
    private int totalTime = 0;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            totalTime++;
            handler.postDelayed(this, 1000);
        }
    };
    private Handler upLoadPicHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String callbackId = bundle.getString("callbackId");
            String answerJson = bundle.getString("answerJson");
            submitAnswer(callbackId, answerJson);

        }
    };

    @Override
    public void onLoadOver() {
        hideTitleBar();
    }

    @Override
    public void onBackFinish() {

    }

    @SuppressLint("NewApi")
    @Override
    public void onBackPressed() {
        try {

            systemWebView.evaluateJavascript("local.getAnswer()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String answer) {
                    Log.e(TAG, "从JS获取的答案：" + answer);
                    exitOnlineAnswer(answer);
                }
            });

        } catch (NoSuchMethodError error) {

        }

    }


    public final ArrayBlockingQueue<String> onPageFinishedUrl = new ArrayBlockingQueue<String>(5);
    protected CordovaInterfaceImpl cordovaInterface = new CordovaInterfaceImpl(this) {
        @Override
        public Object onMessage(String id, Object data) {
            if ("onPageFinished".equals(id)) {
                try {

                    onPageFinishedUrl.add((String) data);

                } catch (IllegalStateException e) {

                }
            }
            return super.onMessage(id, data);
        }
    };


    private void showH5View() {
        isSubmiting = false;
        systemWebView.setVisibility(View.VISIBLE);
        hideTitleBar();
        ll_submiting.setVisibility(View.GONE);
        rel_submit_fail.setVisibility(View.GONE);
    }

    private void showSubmitView() {
        isSubmiting = true;
        showTitleBar();
        systemWebView.setVisibility(View.GONE);
        ll_submiting.setVisibility(View.VISIBLE);
        rel_submit_fail.setVisibility(View.GONE);
    }

    private void showSubmitFailView() {
        isSubmiting = true;
        hideTitleBar();
        systemWebView.setVisibility(View.GONE);
        ll_submiting.setVisibility(View.GONE);
        rel_submit_fail.setVisibility(View.VISIBLE);
    }


    /**
     * 获取在线作答资源
     *
     * @param callbackId
     */
    private void getOnlineExamination(final String callbackId) {
        EpaperDao.getInstance().getResource(mJsonResPath, new BaseExtCallBack(this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(final Object data) {

                result = data.toString();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (OnlineAnswerFrom == 1) {//来自作业
                        jsonObject.put("isWork", 1);
                        jsonObject.put("needDoWorkID", checkResource);
                    } else {
                        jsonObject.put("isWork", 0);//来自书桌
                        jsonObject.put("needDoWorkID", checkResource);//来自书桌
                    }
                    if (doWorkType == 1) {
                        jsonObject.put("errorResource", errorResource);//来自书桌
                    } else {
                        getTotalNum(jsonObject);
                        boolean isSaveStartDate = CWSys.getSharedBoolean(RepeatKeyUtil.getStartDateIsUploadSaveKey(mDownLoadInfo, mModule, position, workId, 0), false);
                        if (!isSaveStartDate) {
                            setDoworkProgress(null);
                        }
                    }
                    sendCallBackSuccess(callbackId, jsonObject.toString());
                } catch (JSONException e) {
                    sendCallBackSuccess(callbackId, result);
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                sendCallBackSuccess(callbackId, data.toString());
                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_ONLINE_ANSWER, "文件不存在==" + mJsonResPath, mDownLoadInfo.getBookName() + " :" + mDownLoadInfo.getChapterName() + " :" + mDownLoadInfo.getUrl());
                ToastUtil.INSTANCE.toastCenterError("文件不存在，请清除缓存后重试");
                finish();
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                sendCallBackSuccess(callbackId, "");
                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_ONLINE_ANSWER, "文件不存在==" + mJsonResPath, mDownLoadInfo.getBookName() + " :" + mDownLoadInfo.getChapterName() + " :" + mDownLoadInfo.getUrl());
                ToastUtil.INSTANCE.toastCenterError("文件不存在，请清除缓存后重试");
                finish();
            }
        });
    }

    /**
     * 获取题目总数
     *
     * @param jsonObject
     */
    private void getTotalNum(JSONObject jsonObject) {
        try {
            JSONArray partsList = jsonObject.getJSONArray("parts");
            /**
             * 选中的资源(同步跟读：id字符串；听说模考：下标字符串)//选择布置的
             * 目前只有听说模考有字段内容，比如一份试卷有10题只选中其中几题布置
             */
            if (!TextUtils.isEmpty(checkResource)) {
                // 有选题
                String[] checkedQuesIndexs = checkResource.split(",");
                for (String quesIndex : checkedQuesIndexs) {
                    int index = Integer.parseInt(quesIndex);
                    if (index < partsList.length()) {
                        JSONObject partsInfo = partsList.getJSONObject(index);
                        //获取到children
                        JSONArray children = partsInfo.getJSONArray("children");
                        for (int j = 0; j < children.length(); j++) {
                            JSONObject childrenInfo = children.getJSONObject(j);
                            boolean ischild = childrenInfo.has("children");
                            if (ischild) {
                                //获取到children2
                                JSONArray children2 = childrenInfo.getJSONArray("children");
                                if (children2.length() <= 0) {
                                    int qtype = childrenInfo.getInt("qtype");
                                    if (qtype == 1 || qtype == 2 || qtype == 4 || qtype == 8) {
                                        total = total + 1;
                                    } else {
                                        JSONArray options = childrenInfo.getJSONArray("options");
                                        total = total + options.length();
                                    }
                                } else {
                                    for (int k = 0; k < children2.length(); k++) {
                                        JSONObject children2Info = children2.getJSONObject(k);
                                        //获取到children2
                                        int qtype = children2Info.getInt("qtype");
                                        if (qtype == 1 || qtype == 2 || qtype == 4 || qtype == 8) {
                                            total = total + 1;
                                        } else {
                                            JSONArray options = children2Info.getJSONArray("options");
                                            total = total + options.length();
                                        }
                                    }
                                }
                            } else {
                                //获取到children
                                int qtype = childrenInfo.getInt("qtype");
                                if (qtype == 1 || qtype == 2 || qtype == 4 || qtype == 8) {
                                    total = total + 1;
                                } else {
                                    JSONArray options = childrenInfo.getJSONArray("options");
                                    total = total + options.length();
                                }
                            }
                        }
                    }
                }
            } else {
                for (int i = 0; i < partsList.length(); i++) {
                    JSONObject partsInfo = partsList.getJSONObject(i);
                    //获取到children
                    JSONArray children = partsInfo.getJSONArray("children");
                    for (int j = 0; j < children.length(); j++) {
                        JSONObject childrenInfo = children.getJSONObject(j);
                        boolean ischild = childrenInfo.has("children");
                        if (ischild) {
                            //获取到children2
                            JSONArray children2 = childrenInfo.getJSONArray("children");
                            if (children2.length() <= 0) {
                                int qtype = childrenInfo.getInt("qtype");
                                if (qtype == 1 || qtype == 2 || qtype == 4 || qtype == 8) {
                                    total = total + 1;
                                } else {
                                    JSONArray options = childrenInfo.getJSONArray("options");
                                    total = total + options.length();
                                }
                            } else {
                                for (int k = 0; k < children2.length(); k++) {
                                    JSONObject children2Info = children2.getJSONObject(k);
                                    //获取到children2
                                    int qtype = children2Info.getInt("qtype");
                                    if (qtype == 1 || qtype == 2 || qtype == 4 || qtype == 8) {
                                        total = total + 1;
                                    } else {
                                        JSONArray options = children2Info.getJSONArray("options");
                                        total = total + options.length();
                                    }
                                }
                            }
                        } else {
                            //获取到children
                            int qtype = childrenInfo.getInt("qtype");
                            if (qtype == 1 || qtype == 2 || qtype == 4 || qtype == 8) {
                                total = total + 1;
                            } else {
                                JSONArray options = childrenInfo.getJSONArray("options");
                                total = total + options.length();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendCallBackFail(String callbackId, String error) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.error(error);
    }

    private void sendCallBackSuccess(String callbackId, String result) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.success(result);
    }

    private void sendCallBackSuccess(String callbackId, JSONObject result) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.success(result);
    }

    private void sendCallBackSuccess(String callbackId, int result) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.success(result);
    }

    public CordovaWebView getCordovaWebView() {
        return cordovaWebView;
    }

    @Override
    protected void onDestroy() {
        ALiYunManager.getInstance().unRegisterListener(aLiYunListener);
        isjumpToResult = false;
        EventBus.getDefault().unregister(this);


        if (systemWebView != null)
            systemWebView.destroy();
        if (cordovaWebView != null)
            cordovaWebView.getEngine().destroy();
        if (cordovaWebView != null)
            cordovaWebView.getPluginManager().onDestroy();
        super.onDestroy();
    }


    @Override
    public void finish() {
        isjumpToResult = false;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ViewGroup view = (ViewGroup) getWindow().getDecorView();
                view.setBackgroundColor(getResources().getColor(R.color.white));
                for (int i = 0; i < view.getChildCount(); i++) {
                    if (view.getChildAt(i).getParent() != null) {
                        view.removeView(view.getChildAt(i));
                    }
                }
                NewWorkOnlineAnswerCordovaActivity.super.finish();
            }
        });
    }

    /**
     * 未完成作业提交提醒窗口
     */
    public void showConfirmCommitDialog(final Activity context, final String tips, final String callbackId, final String answerJson) {
        CWDialog dialog = new CWDialog(context);
        dialog.setMessage(tips);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                submitAnswer(callbackId, answerJson);

                            }
                        })
                .show();
    }

    private ALiYunManager.ALiYunListener aLiYunListener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {

        }

        @Override
        public void onSuccess(Object tag, String url) {
            try {
                OnlineAnswerPhotoBean onlineAnswerPhotoBean = (OnlineAnswerPhotoBean) tag;
                for (OnlineAnswerPhotoBean answerPhotoBean : onlineAnswerPhotoBeans) {
                    if (answerPhotoBean.photoPath.equals(onlineAnswerPhotoBean.photoPath)) {
                        answerPhotoBean.photoUrl = url;
                        //                        onlineAnswerPhotoBeans.remove(answerPhotoBean);
                    }
                }
            } catch (Exception e) {
                showToastError("图片上传失败，请重试");
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Object tag, int errorCode) {
            if (tag != null) {
                //                OnlineAnswerPhotoBean onlineAnswerPhotoBean = (OnlineAnswerPhotoBean) tag;
                //                ALiYunManager.getInstance().addPic(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
            }
            ToastUtil.INSTANCE.toastCenterError(errorCode + "图片上传失败，重试中..");
        }
    };

    @Override
    protected void onResume() {
        isjumpToResult = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        isjumpToResult = false;
        super.onPause();
        String saveTimeKey = ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, workId, mUuid);
        CWSys.setSharedInt(saveTimeKey, totalTime);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_submit_again) {//重新提交
            if (!NetworkUtils.isOnline()) {
                ToastUtil.INSTANCE.toastCenterNoNetError();
                return;
            }
            Log.d(TAG, "######onClick answerJson#########" + answerJson);

            submitAnswer(callbackId, answerJson);
        }
    }

    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    private List<OnlineAnswerPhotoBean> onlineAnswerPhotoBeans = new ArrayList<OnlineAnswerPhotoBean>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if (requestCode == NewLoginActivity.FOR_LOGIN) {//顶号后重新登录成功
                finish();

            } else if (requestCode == PHOTO_REQUEST_CAMERA) {//拍照答题
                try {
                    String tempCameraFile = ESystem.getImagesPath(NewWorkOnlineAnswerCordovaActivity.this) + File.separator + "temp.jpg";
                    String outputPath = FileUtil.compressImage(tempCameraFile, mCameraPath, 100);
                    OnlineAnswerPhotoBean onlineAnswerPhotoBean = new OnlineAnswerPhotoBean();
                    onlineAnswerPhotoBean.photoPath = outputPath;
                    onlineAnswerPhotoBean.callbackId = callbackId;
                    ALiYunManager.getInstance().addPic(outputPath, onlineAnswerPhotoBean);
                    String photoUrlKey = ALiYunManager.getInstance().getPicKey(outputPath);
                    String photoUrl = ALiYunManager.ACCESS_URL + photoUrlKey;
                    //                    onlineAnswerPhotoBean.photoUrl = photoUrl;
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("photoPath", outputPath);
                    jsonObject.put("photoUrl", photoUrl);
                    onlineAnswerPhotoBeans.add(onlineAnswerPhotoBean);
                    sendCallBackSuccess(onlineAnswerPhotoBean.callbackId, jsonObject);
                } catch (Exception e) {
                    showToastError("获取图片失败，请重新拍照上传");
                    CWLog.e("获取图片失败", "获取图片失败");
                    e.printStackTrace();
                }
            } else if (requestCode == TAKE_PHOTOFORPAD) {
                try {
                    OnlineAnswerPhotoBean onlineAnswerPhotoBean = new OnlineAnswerPhotoBean();
                    String photoUrlKey = ALiYunManager.getInstance().getPicKey(mCameraPath);
                    String photoUrl = ALiYunManager.ACCESS_URL + photoUrlKey;
                    onlineAnswerPhotoBean.photoPath = mCameraPath;
                    onlineAnswerPhotoBean.callbackId = callbackId;
                    ALiYunManager.getInstance().addPic(mCameraPath, onlineAnswerPhotoBean);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("photoPath", mCameraPath);
                    jsonObject.put("photoUrl", photoUrl);
                    onlineAnswerPhotoBeans.add(onlineAnswerPhotoBean);
                    sendCallBackSuccess(onlineAnswerPhotoBean.callbackId, jsonObject);
                } catch (Exception e) {
                    showToastError("获取图片失败，请重新拍照上传");
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 清除记录
     */
    private void clearRecord() {
        //        清除本次做作业或自主练习活动key,只有活动key 清
        Log.d(TAG, "#######clearRecord #########");
        CWSys.setSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, 0), null);
        CWSys.setSharedLong(RepeatKeyUtil.getStartDateSaveKey(mDownLoadInfo, mModule, position, workId, 0), 0);
        SerializableManager.getInstance().serialize(getOnLineAnswerKey(), null);
        ESystem.setSharedString(getOnLineAnswerKey(), null);
        //上传成功 清除保存的开始时间
        CWSys.setSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, workId), 0);
    }


}
